package movie;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


import com.google.gson.Gson;

import datamodel.MovieInfo;

public class IMDB_getMovieInfo {
	
	private String MovieName = null , Year = null, apiurl = "http://www.deanclatworthy.com/imdb/";
	private MovieInfo movieinfo;
	
	public IMDB_getMovieInfo(String MovieName, String Year, MovieInfo movieinfo){
		this.MovieName = MovieName;
		this.Year = Year;
		this.setMovieinfo(movieinfo);
	}
	
	public IMDB_getMovieInfo(String MovieName, MovieInfo test){
		this.MovieName = MovieName;
		this.setMovieinfo(movieinfo);
	}

	// Get movie information from IMDB.
	public void getMovieinfo() {
		InputStream is = null;
		BufferedReader dis = null;
		URL url = null;
		String dataurl = null;
		
		// Remove unwanted spaces and replace space with + sign.
		this.MovieName.trim();
		this.MovieName = this.MovieName.replace(" ", "+");
		
		if(Year != null){ 
			dataurl=apiurl+"?q="+this.MovieName+"&year="+this.Year+"&type=json";	
		} else {
			dataurl=apiurl+"?q="+this.MovieName+"&type=json";
		}
		
		try {
			url = new URL(dataurl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   

		try {
			is = url.openStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		dis = new BufferedReader(new InputStreamReader(is));
		Gson gson = new Gson();
		
		try {
			String details = dis.readLine();
			this.setMovieinfo(gson.fromJson(details, MovieInfo.class));
			//System.out.println(this.test.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public MovieInfo getTest() {
		return movieinfo;
	}

	public void setMovieinfo(MovieInfo movieinfo) {
		this.movieinfo = movieinfo;
	}

}
